package mysql

import (
	"context"
	"go.uber.org/zap"
	"gorm.io/gorm"
	log "maya-service/collector/logger"
	"maya-service/config"
	"maya-service/model"
	"maya-service/model/entity"
	"maya-service/utils"
)

var AnswerRecord = &answerRecord{}

type answerRecord struct{}

func init() {
	Register(AnswerRecord)
}

func (a *answerRecord) Init() {
	if config.Conf.AutoMigrate {
		p := &entity.AnswerRecord{}
		if db.Migrator().HasTable(p) {
			log.Debug("table already exist: ", zap.String("table", p.TableName()))
			return
		}
		if err := db.AutoMigrate(p); err != nil {
			log.Error("filed to create table please check config or manually create", zap.String("table", p.TableName()), zap.String("err", err.Error()))
		} else {
			log.Info("create table successfully", zap.String("table", p.TableName()))
		}
	}
}

// Create
func (a *answerRecord) Create(ctx context.Context, m *entity.AnswerRecord) (int64, error) {
	err := GetDB(ctx).Create(m).Error
	return m.Id, err
}

// Find detail
func (a *answerRecord) Find(ctx context.Context, in *model.AnswerRecordInfoRequest) (*entity.AnswerRecord, error) {
	e := &entity.AnswerRecord{}

	q := GetDB(ctx).Model(&entity.AnswerRecord{})

	if in.Id > 0 {
		q = q.Where("id = ?", in.Id)
	}

	if in.UserId != "" {
		q = q.Where("user_id = ?", in.UserId)
	}

	if in.FirstLevel > 0 {
		q = q.Where("first_level = ?", in.FirstLevel)
	}

	if in.SecondLevel > 0 {
		q = q.Where("second_level = ?", in.SecondLevel)
	}
	err := q.First(&e).Error
	return e, err
}

// Update
func (a *answerRecord) Update(ctx context.Context, id int64, dict map[string]interface{}) error {
	return GetDB(ctx).Model(&entity.AnswerRecord{}).Where("id = ?", id).Updates(dict).Error
}

// Delete
func (a *answerRecord) Delete(ctx context.Context, id int64) error {
	return GetDB(ctx).Delete(&entity.AnswerRecord{}, id).Error
}

// List query list
func (a *answerRecord) List(ctx context.Context, in *model.AnswerRecordListRequest) (int, []*entity.AnswerRecord, error) {
	var (
		q             = GetDB(ctx).Model(&entity.AnswerRecord{})
		err           error
		total         int64
		answerRecords []*entity.AnswerRecord
	)

	if in.UserId != nil {

		q = q.Where("user_id = ?", in.UserId)

	}

	if in.Difficulty != nil {

		q = q.Where("difficulty = ?", in.Difficulty)

	}

	if in.FirstLevel != nil {

		q = q.Where("first_level = ?", in.FirstLevel)

	}

	if in.SecondLevel != nil {

		q = q.Where("second_level = ?", in.SecondLevel)

	}

	if in.Desc != nil {

		q = q.Where("`desc` like ?", utils.SqlLike(in.Desc))

	}

	if in.AnswerValue != nil {

		q = q.Where("answer_value like ?", utils.SqlLike(in.AnswerValue))

	}

	if in.CorrectNum != nil {

		q = q.Where("correct_num = ?", in.CorrectNum)

	}

	if in.Total != nil {

		q = q.Where("total = ?", in.Total)

	}

	if in.Star != nil {

		q = q.Where("star = ?", in.Star)

	}

	if in.CreatedAt != nil {

		q = q.Where("created_at = ?", in.CreatedAt)

	}

	if in.UpdatedAt != nil {

		q = q.Where("updated_at = ?", in.UpdatedAt)

	}

	if err = q.Count(&total).Error; err != nil {
		return 0, nil, err
	}
	if err = q.Limit(in.Size).Offset((in.Index - 1) * in.Size).Find(&answerRecords).Error; err != nil {
		return 0, nil, err
	}
	return int(total), answerRecords, nil
}

// ExecTransaction execute database transaction
func (a *answerRecord) ExecTransaction(ctx context.Context, callback func(ctx context.Context) error) error {
	return GetDB(ctx).Transaction(func(tx *gorm.DB) error {
		ctx = context.WithValue(ctx, ContextTxKey, tx)
		return callback(ctx)
	})
}
